//
//  ViewController.m
//  0.3camera
//
//  Created by 茶 on 2023/11/23.
//

#import "HomeViewController.h"
#import "CATexture.h"
#import "CACameraCapture.h"
#import "CAVipAlertView.h"
#import "HomeView.h"
#import "CAADManager.h"

#import <TZImagePickerController/TZImagePickerController.h>
@import RyukieSwifty;

@interface HomeViewController () <TZImagePickerControllerDelegate, OTCameraBufferDelegate>

@property (nonatomic, strong) HomeView *homeView;

@property (nonatomic, strong) CACameraCapture *caputre;
@property (nonatomic, strong) STDSGLImageParam *imgLayer1;
@property (nonatomic, strong) STDSGLImageParam *imgLayer2;
@property (nonatomic, strong) CATexture *inputText;

@property (nonatomic, strong) NSString *imagePath;
@property (nonatomic, strong) NSString *lutPath;

@end

@implementation HomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initInterface];
    [self initEvent];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [_caputre startRunning];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [_caputre stopRunning];
}

- (void)initInterface {
    self.view.backgroundColor = UIColor.whiteColor;
    ScreenShieldView *view = [ScreenShieldView createWithFrame:self.view.frame];
    _homeView = [[HomeView alloc] initWithFrame:self.view.frame];
    [self.view addSubview:view];
    [view addSubview:_homeView];
    
    _caputre = [[CACameraCapture alloc] initCamera];
    _caputre.delegate = self;
    
    
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"Home_Mine"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(pushMineVC)];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"Home_QA"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(pushQuestionVC)];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    [[CAADManager sharedInstance] bannerAdEventWithController:self];
}

- (void)initEvent {
    CAWeakify(self);
    _homeView.btnBlock = ^(NSUInteger index) {
        CAStrongify(self);
        if (index == 0) {
            [self.navigationController pushViewController:[NSClassFromString(@"SavedViewController") new] animated:YES];
        } else if (index == 1) {
            if (self.homeView.count < 10) {
                [self takePhotoEvent];
            } else {
                if (kUserModel.vipStatus) {
                    [self takePhotoEvent];
                } else {
                    [CAVipAlertView showWithTitle:@"继续使用该功能需要VIP" completionBlock:^{
                        CAStrongify(self);
                        [self.navigationController pushViewController:[NSClassFromString(@"CAVipViewController") new] animated:YES];
                    }];
                }
                
            }
        } else if (index == 2) {
            if (kUserModel.vipStatus) {
                [self imagePickerEvent];
            } else {
                [CAVipAlertView showWithTitle:@"使用该功能需要VIP" completionBlock:^{
                    CAStrongify(self);
                    [self.navigationController pushViewController:[NSClassFromString(@"CAVipViewController") new] animated:YES];
                }];
            }
        }
    };
    _homeView.switchBlock = ^(BOOL isFront) {
        CAStrongify(self);
        self.caputre.isFront = isFront;
    };
    
}

- (void)takePhotoEvent {
    if (_homeView.count < 10) {
        _homeView.count += 1;
        [kUserModel setPhotoCountWithValue:_homeView.count];
    }
    if (_homeView.count == 2) {
        [UIDevice showSystemReview];
    }
    
    UIImpactFeedbackGenerator *generator = [[UIImpactFeedbackGenerator alloc] initWithStyle:UIImpactFeedbackStyleLight];
    [generator impactOccurred];
    CAWeakify(self);
    [_homeView.displayView takeImageWithComplate:^(UIImage * _Nonnull image) {
        CAStrongify(self);
        UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
        [self saveDocumentsImageWithImage:image];
    }];
}

- (void)imagePickerEvent {
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
    imagePickerVc.allowTakeVideo = NO;
    imagePickerVc.allowEditVideo = NO;
    imagePickerVc.allowPickingVideo = NO;
    imagePickerVc.allowTakePicture = NO;
    CAWeakify(self);
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        CAStrongify(self);
        UIImage *oriImage = photos.firstObject;
        NSString * path = [NSString stringWithFormat:@"%@temp", NSTemporaryDirectory()];
        NSString * imgPath = [path stringByAppendingString:[NSString stringWithFormat:@"/%.0f.png", [[NSDate date] timeIntervalSince1970]]];
        if (![[NSFileManager defaultManager] fileExistsAtPath:path]){
            [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
        }
        [UIImagePNGRepresentation(oriImage) writeToFile:imgPath atomically:YES];
        [self.caputre stopRunning];
    
        [SVProgressHUD show];
        self.imagePath = imgPath;
        if (self.homeView.displayView && self.imgLayer1 && self.imgLayer2) {
            [self.homeView.displayView replaceLayerAssetImgPath:self.imagePath layerID:self.imgLayer1.layerID];
            [self.homeView.displayView replaceLayerAssetImgPath:self.imagePath layerID:self.imgLayer2.layerID];
        }
        [self.homeView.displayView takeImageWithComplate:^(UIImage * _Nonnull image) {
            CAStrongify(self);
            UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
            [self saveDocumentsImageWithImage:image];
            [self.caputre startRunning];
            [SVProgressHUD dismiss];
            [UIDevice showSystemReview];
        }];
    }];
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}

- (void)pushMineVC {
    [self.navigationController pushViewController:[NSClassFromString(@"MineViewController") new] animated:YES];
}

- (void)pushQuestionVC {
    [self.navigationController pushViewController:[NSClassFromString(@"QuestionViewController") new] animated:YES];
}

#pragma mark -- Private Method
- (void)saveDocumentsImageWithImage:(UIImage *)image {
    NSString * path = [NSString stringWithFormat:@"%@/image", NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject];
    NSString * imgPath = [path stringByAppendingString:[NSString stringWithFormat:@"/%.0f.png", [[NSDate date] timeIntervalSince1970]]];
    if (![[NSFileManager defaultManager] fileExistsAtPath:path]){
        [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
    }
    NSError *error = nil;
    [UIImagePNGRepresentation(image) writeToFile:imgPath options:NSDataWritingAtomic error:&error];
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    NSString *msg = nil ;
    NSLog(@"image = %@, error = %@, contextInfo = %@", image, error, contextInfo);
    if(error != NULL){
        msg = @"保存图片失败" ;
    }else{
        msg = @"保存图片成功" ;
    }
    [self.view makeToast:msg];
    NSLog(@"+++++++++++%@", msg);
}

- (void)setupLayer:(CATexture *)texture {
    _imgLayer1 = [_homeView.displayView.renderer addImageLayerWithTextureID:texture.originalTexture width:texture.width height:texture.height];
    _imgLayer2 = [_homeView.displayView.renderer addImageLayerWithTextureID:texture.originalTexture width:texture.width height:texture.height];
    [self processRenderView:_homeView.displayView];
}

- (void)processRenderView:(STDSRenderView *)view {
    [view.renderer selectLayer:_imgLayer1.layerID];
    [view addEffectType:STDSEffectTypeColorGrain];
    [view addEffectType:STDSEffectTypeGaussianBlur];
    
    [view.renderer changeEffectArguments:STDSEffectTypeColorGrain name:@"garub" floatValue:20.0];
    [view.renderer changeEffectArguments:STDSEffectTypeGaussianBlur name:@"radius" floatValue:5.0];
    
    [view.renderer selectLayer:_imgLayer2.layerID];
    [view.renderer setLayerAlpha:0.8];
    [view.renderer setBlend:STDSBlendTypeScreen];
    
    [view addEffectType:STDSEffectTypeColorGrain];
    [view addEffectType:STDSEffectTypeGaussianBlur];
    [view addEffectType:STDSEffectTypeGlowLight];

    [view.renderer changeEffectArguments:STDSEffectTypeColorGrain name:@"grain" floatValue:20.0];
    [view.renderer changeEffectArguments:STDSEffectTypeGaussianBlur name:@"radius" floatValue:5.0];
    [view.renderer changeEffectArguments:STDSEffectTypeGlowLight name:@"param1" floatValue:0.5];
    
    [view.renderer selectLayer:_homeView.compose.layerID];
    [view addEffectType:STDSEffectTypeLut];
    [view.renderer changeEffectArguments:STDSEffectTypeLut name:@"lut" stringValue:self.lutPath];
    [view.renderer changeEffectArguments:STDSEffectTypeLut name:@"alpha" floatValue:0.4];
}


#pragma mark -- OTCameraBufferDelegate
- (void)camera:(CACameraCapture *)camera processFrame:(CVPixelBufferRef)pixelBuffer {
    CAWeakify(self);
    CVPixelBufferRetain(pixelBuffer);
    [_homeView.displayView onRendererThreadBlock:^(STDSRenderView * _Nonnull renderView) {
        CAStrongify(self);
        if (self.inputText) {
            [self.inputText setupTexture:pixelBuffer];
            if (self.imgLayer1 && self.imgLayer2) {
                [renderView.renderer selectLayer:self.imgLayer1.layerID];
                [renderView.renderer replaceLayerTextureID:self.inputText.originalTexture width:self.inputText.width height:self.inputText.height];
                
                [renderView.renderer selectLayer:self.imgLayer2.layerID];
                [renderView.renderer replaceLayerTextureID:self.inputText.originalTexture width:self.inputText.width height:self.inputText.height];
            } else {
                [self setupLayer:self.inputText];
            }
        }
        [renderView render];
    }];
}

#pragma mark --lazyLoading
- (NSString *)lutPath {
    if (_lutPath) return _lutPath;
    _lutPath = [[NSBundle mainBundle] pathForResource:@"HUJI.jpg" ofType:@""];
    return _lutPath;
}
- (CATexture *)inputText {
    if (_inputText) return _inputText;
    _inputText = [CATexture new];
    return _inputText;
}
@end
